﻿using System;
using LuaVM.Core;
using MFGLib;

namespace Plugin.DC
{
    public class DCPlugin : LuaDllPlugin
	{
		public override string Name => "DC";

		private LuaTable m_table = null;
		private MemDC m_dc = null;

		public override string[] ExportedVariables => new string[] {
			"COLOR_INVALID"
		};

		public override string[] ExportedFunctions => new string[] {
			"RGBCombine",
			"RGBSplit",
			"GetPixel",
			"WaitForPixel",
			"CapturePixelBlock"
		};

		protected override void OnAttach()
		{
			base.OnAttach();
			m_dc = new MemDC();

			m_table = NewTable();

			RegisterVariable("COLOR_INVALID", MemDC.COLOR_INVALID);

			RegisterFunction<DCPlugin>("RGBCombine");
			RegisterFunction<DCPlugin>("RGBSplit");
			RegisterFunction(this, "GetPixel");
			RegisterFunction(this, "WaitForPixel");
			RegisterFunction(this, "CapturePixelBlock");
		}

		protected override void OnDetach()
		{
			base.OnDetach();
			m_dc.Dispose();
			m_dc = null;
		}		

		public static int RGBCombine(byte r, byte g, byte b)
		{
			return MemDC.RGB(r, g, b);
		}

		public static byte? RGBSplit(int color, out byte? g, out byte? b)
		{
			if (color == MemDC.COLOR_INVALID)
			{
				g = null;
				b = null;
				return null;
			}

			g = MemDC.GetGValue(color);
			b = MemDC.GetBValue(color);
			return MemDC.GetRValue(color);
		}

		public int GetPixel(int x, int y)
		{
			return m_dc.CaptureAndGetPixel(x, y);
		}

		public bool WaitForPixel(int x, int y, int color, int timeout)
		{
			return m_dc.WaitForPixel(x, y, color, timeout);
		}

		public object CapturePixelBlock(int x, int y, int width, int height)
		{
			if (!m_dc.Capture(x, y, width, height))
			{
				return null;
			}

			m_table.Clear();
			int index = 0;

			for (int i = 0; i < width; i++)
			{
				for (int j = 0; j < height; j++)
				{
					index++;
					m_table[index] = m_dc.GetPixel(i, j); // Lua数组下标为1-n
				}
			}

			return m_table.Table;
		}
	}
}
